import QualityInspectionApi from '../../../common/api/feed/qualityinspectionList.api.js';

(function(window, document, $) {
	let _vm, detailId = null;

	$(function() {
		// 初始化Vue实例
		_vm = new Vue({
			el: "#main",
			data: {
				bizDate: '',
				companyName: '',
				inspectionTypeName: '',
				qualityResultsName: '',
				materialName: '',
				waybillNo: '',
				vehicleNo: '',
				basicUnit: '',
				quantity: ''
			}
		});

		// 强制光明模式
		$('body').attr('data-weui-theme', 'light');

		// 获取URL参数中的id
		detailId = getUrlKey('id');

		// 如果有id，加载详情数据
		if (detailId) {
			_loadDetailData();
		} else {
			$.toptip('缺少质检单ID参数', 'warning');
		}
	});

	// 加载详情数据
	const _loadDetailData = async () => {
		try {
			$.showLoading('加载中...');
			const response = await QualityInspectionApi.getInspectionOrderDetails(detailId);

			if (response) {
				const data = response;

				// 设置业务日期
				_vm.bizDate = data.bizFormObj?.bizDate
					? moment(data.bizFormObj.bizDate).format('YYYY-MM-DD')
					: '';

				// 设置公司名称
				_vm.companyName = data.company?.name || '';

				// 设置质检类型（1=原料质检, 2=成品质检）
				if (data.type !== undefined && data.type !== null) {
					_vm.inspectionTypeName = data.type === 1 ? '原料质检' :
											  data.type === 2 ? '成品质检' : '';
				}

				// 设置质检结果（1=合格, 2=不合格）
				if (data.qualityResults !== undefined && data.qualityResults !== null) {
					_vm.qualityResultsName = data.qualityResults === 1 ? '合格' :
											 data.qualityResults === 2 ? '不合格' : '';
				}

				// 设置物料名称（包含编号）
				if (data.material?.name) {
					_vm.materialName = data.material.numCode
						? `${data.material.name}(${data.material.numCode})`
						: data.material.name;
				}

				// 设置其他字段
				_vm.waybillNo = data.waybillNo || '';
				_vm.vehicleNo = data.vehicleNo || '';
				_vm.basicUnit = data.basicUnit || '';
				_vm.quantity = data.quantity || '';

				$.hideLoading();
			}
		} catch (error) {
			$.hideLoading();
			console.error('加载详情数据失败:', error);
			$.toptip('加载数据失败', 'error');
		}
	};

	// 获取URL参数
	const getUrlKey = (name) => {
		const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		const r = window.location.search.substr(1).match(reg);
		if (r != null) return decodeURIComponent(r[2]);
		return null;
	};

})(window, document, jQuery);
